/**
 * 
 */
package com.cr.backbone.ajax.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.opensymphony.xwork2.ActionSupport;
import com.readnote.book.model.UserBook;
import com.readnote.book.service.UserBookService;
import com.readnote.user.model.User;

/**
 * @project RaedNote
 * @version 1.0
 * @company 
 * @fileDescribe
 * @fileType AjaxTest AjaxTest.java
 * @author xianghua.hu
 * @date 2012-5-16 下午04:24:43
 */
/**
 * @author huxh
 *
 */
public class AjaxTestAction extends ActionSupport  implements ServletRequestAware, ServletResponseAware {
	private Long userId;
	private UserBookService userBookService;
	private String ajaxNodes;
	
	
	private String name="张三";//名字参数
	private String helloword="";
	private HttpServletRequest req;
	private HttpServletResponse resp;
	

	/**
	 * 
	 * 接收请求：（各种js异步请求提交方式jqeruy）ajax 提交异步请求后，接收一个http请求，产生： HttpServletRequest\ HttpServletResponse。
	 * 业务处理：业务处理完毕以后，返回处理结果。
	 * 相应传输：处理完毕以后， HttpServletResponse 返回相应字符流。可以以text/html 返回html；可以返回xml格式的xml数据；可以返回json格式的数据等等
	 * 客户端接收请求并展示处理结果：客户端通过js(jquery)获取结果数据（html文本,xml，json）等格式的数据并进行解析，将解析结果动态显示到当前页面
	 * 
	 * 
	 * 问题1：提交和解析请求js代码繁琐
	 * 解决办法：使用Ｊｑｕｅｒｙ等框架简化
	 * 问题2：客户端提交请求参数格式、服务端处理并返回结果数据格式如果不统一，那么提交、响应处理过于繁杂
	 * 解决办法：统一使用同一种数据格式：xml\html\json等
	 * 
	 * @return
	 * @throws IOException
	 * @author xianghua.hu
	 * @date 2012-5-17
	 */
	public String helloPrintOut() throws IOException{
		helloword="你好，"+name;
		System.out.println("helloPrintOut:"+helloword);
		
		 req.setCharacterEncoding("UTF-8");   
	     resp.setContentType("text/html;charset=UTF-8");   
	     PrintWriter out = resp.getWriter();   
	     //执行你的操作代码、   
	     out.write(helloword);
	     return null;

	}
	
	public String hello() {
		helloword="你好，"+name;
		System.out.println(helloword);
		userId=1l;
		return SUCCESS;
	}
	
	public String ajax() throws Exception {  
        String JSON_text = "";  
        if (userId == 0) {  
            JSON_text = "[{optionValue:'0',optionDisplay:'--请选择--'}]";  
            
        } else {  
            User user=new User(userId);
			List<UserBook> ubooks = userBookService  
                    .getListUserBookByUser(user);  
            if (ubooks.size() > 0) {  
                JSON_text = "[";  
                for (int i = 0; i < ubooks.size(); i++) {  
                    UserBook sub = ubooks.get(i);  
                    JSON_text += "{optionValue:'" + sub.getId()  
                            + "',optionDisplay:'bookId_" + sub.getBook().getId() + "'}";  
                    if (i < ubooks.size() - 1) {  
                        JSON_text += ", ";  
                    } else if (i == ubooks.size() - 1) {  
                        JSON_text += "]";  
                    }  
                }  
            }  
        }  
//        PrintWriter out = null;  
//        try {  
//            ServletActionContext.getResponse().setCharacterEncoding("UTF-8");  
//            out = ServletActionContext.getResponse().getWriter();  
//        } catch (IOException ex) {  
//            ex.printStackTrace();  
//        }  
//        System.out.println(JSON_text);
//        out.write(JSON_text);  
//        out.close();
        ajaxNodes=JSON_text;
        System.out.println(ajaxNodes);
        return SUCCESS;
    }

	public Long getUserId() {
		return userId;
	}

	public void setUserId(Long userId) {
		this.userId = userId;
	}

	public UserBookService getUserBookService() {
		return userBookService;
	}

	public void setUserBookService(UserBookService userBookService) {
		this.userBookService = userBookService;
	}

	
	public String getAjaxNodes() {
		return ajaxNodes;
	}

	public void setAjaxNodes(String ajaxNodes) {
		this.ajaxNodes = ajaxNodes;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getHelloword() {
		return helloword;
	}

	public void setHelloword(String helloword) {
		this.helloword = helloword;
	}

	/* (non-Javadoc)
	 * @see org.apache.struts2.interceptor.ServletRequestAware#setServletRequest(javax.servlet.http.HttpServletRequest)
	 */
	public void setServletRequest(HttpServletRequest arg0) {
		req=arg0;
	}

	/* (non-Javadoc)
	 * @see org.apache.struts2.interceptor.ServletResponseAware#setServletResponse(javax.servlet.http.HttpServletResponse)
	 */
	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		resp=arg0;
	}

	public HttpServletRequest getReq() {
		return req;
	}

	public void setReq(HttpServletRequest req) {
		this.req = req;
	}

	public HttpServletResponse getResp() {
		return resp;
	}

	public void setResp(HttpServletResponse resp) {
		this.resp = resp;
	}  

}
 